/**
 *	all functions related to the 'FindMatchPage' view
**/

if (typeof Controllers === "undefined") {
	var Controllers = { }
}

Controllers.FindMatchPage = {
	
	//run this function every time we visit this page. this cleans up all info and begins a search.
	begin: function() {
		var el = {
			indicator: document.getElementById('FMPindicator'),
			list: document.getElementById('FMPlist')
		}
		
		//set the indicator to show that we are searching
		el.indicator.textContent = 'loading...'
		
		//clear the last game list, if one existed
		while (el.list.hasChildNodes()) {
			el.list.removeChild(el.list.firstChild)
		}
		
		//begin the search process
		MatchSearch.find()
	},
	
	//makes and displays the list of games
	createGamesList: function() {
		var el = {
			indicator: document.getElementById('FMPindicator'),
			list: document.getElementById('FMPlist')
		}
		
		//get the games list API response
		var games = MatchSearch.getList().games
		
		//show some useful info
		el.indicator.textContent = 'number games found: ' + games.length
		
		//display all the games shown
		for (var i=0; i<games.length; i++) {
			var li = document.createElement('li')
			Main.setupButton(li)						//prevent the user from highlighting things
			
			li.innerHTML = "opponent: <span class='info'>" + games[i].players[0] + "</span>"
			var div = document.createElement('div')
			div.className = 'button'
			div.textContent = 'play'
			div.onclick = this._clickMaker(i)
			li.appendChild(div)
			
			el.list.appendChild(li)
		}
	},
	
	//run this when 'play' is clicked
	_clickMaker: function(i) {
		var that = this;
		
		return function() {
			var game = MatchSearch.getList().games[i]
			
			//join the game on the server
			API.joinGame(
				{
					gameId: game.gameId,
					playerName: Main.clientInfo.user
				},
				that._callback
			)
		}
	},
	
	_callback: function(payload) {
		var newGame = JSON.parse(payload)
		
		Main.goTo('GamePage')
		Game.setUpGame(newGame)
	}
	
}